package com.rnkrsoft.suyan.config.gateway.web.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.rnkrsoft.suyan.config.gateway.services.ConfigService;
import com.rnkrsoft.suyan.config.protocol.v2.*;
import com.rnkrsoft.suyan.config.server.config.dao.FileInfoDAO;
import com.rnkrsoft.suyan.config.server.config.dao.MachineInfoDAO;
import com.rnkrsoft.suyan.config.server.config.entity.FileInfoEntity;
import com.rnkrsoft.suyan.config.server.config.entity.MachineInfoEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

@Controller
@RequestMapping("/config")
@Slf4j
public class GatewayController {
    @Autowired
    private ConfigService configService;

    @Autowired
    private FileInfoDAO fileInfoDAO;

    @Autowired
    private MachineInfoDAO machineInfoDAO;

    static Gson GSON = new GsonBuilder().serializeNulls().create();

    @RequestMapping(value = "/fetch", method = RequestMethod.POST)
    @ResponseBody
    public String fetch(@RequestBody String requestJson){
        FetchRequest request = GSON.fromJson(requestJson, FetchRequest.class);
        FetchResponse response = configService.fetch(request);
        String responseJson = GSON.toJson(response);
        return responseJson;
    }

    @RequestMapping(value = "/getParam", method = RequestMethod.POST)
    @ResponseBody
    public String getParam(@RequestBody String requestJson){
        GetParamRequest request = GSON.fromJson(requestJson, GetParamRequest.class);
        GetParamResponse response = configService.getParam(request);
        String responseJson = GSON.toJson(response);
        return responseJson;
    }

    @RequestMapping(value = "/push", method = RequestMethod.POST)
    @ResponseBody
    public String push(@RequestBody String requestJson){
        PushRequest request = GSON.fromJson(requestJson, PushRequest.class);
        PushResponse response = configService.push(request);
        String responseJson = GSON.toJson(response);
        return responseJson;
    }


    @RequestMapping("/download.do")
    @ResponseBody
    public void download(@PathVariable(value = "fileId") String fileId, @PathVariable(value = "token") String token, HttpServletRequest request, HttpServletResponse response) {
        FileInfoEntity fileInfoEntity = fileInfoDAO.selectByPrimaryKey(fileId);
        if (fileInfoEntity == null){
            log.error("文件不存在");
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        MachineInfoEntity machineInfoEntity = machineInfoDAO.selectByPrimaryKey(fileInfoEntity.getMachineId());
        if (machineInfoEntity == null){
            log.error("机器不存在");
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        String securityKey = machineInfoEntity.getSecurityKey();
        String timestamp = Aes.decrypt(securityKey, Aes.DEFAULT_IV, token);
        Long ts = Long.parseLong(timestamp);
        if (ts - System.currentTimeMillis() > 60 * 1000 || System.currentTimeMillis() - ts > 60 * 1000) {
            log.error("TOKEN无效");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        String realFileName = fileInfoEntity.getRealFileName();
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            byte[] data = FileUtils.readFileToByteArray(new File(realFileName));
            IOUtils.write(data, os);
        } catch (IOException e) {
            log.error("读取文件失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }finally {
            IOUtils.closeQuietly(os);
        }
    }
}
